package com.easy.carl.algorithm.tree;

import com.easy.leetcode.tree.TreeNode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

//94. 二叉树的中序遍历
public class InorderTraversal {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        inorder(root, res);
        return res;
    }

    public void inorder(TreeNode root, List<Integer> res) {
        if (root == null) {
            return;
        }
        inorder(root.left, res);
        res.add(root.val);
        inorder(root.right, res);
    }

    public List<Integer> inorderTraversal1(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Deque<TreeNode> deque = new ArrayDeque<>();
        if (root==null) {
            return res;
        }
        TreeNode cur =root;
        while (cur!=null||!deque.isEmpty()){
            if (cur!=null){
                deque.push(cur);
                cur=cur.left;
            }else {
                cur=deque.pop();
                res.add(cur.val);
                cur=cur.right;
            }
        }
        return res;
    }
}
